using System;
using System.Collections.Generic;
using SurveySez.Model;
using UpdateControls;

namespace SurveySez.NavigationModel
{
    public class RoundNavigation : IDisposable
	{
		private Survey _survey;

		private HashSet<Response> _guessedAnswers = new HashSet<Response>();
		private int _incorrectGuesses = 0;
		private PendingOutcome _pendingOutcome;
		private Independent _indGuessedAnswers = new Independent();
		private Independent _indIncorrectGuesses = new Independent();
		private Independent _indPendingOutcome = new Independent();

		public RoundNavigation(Survey survey)
		{
			_survey = survey;
		}

		public Survey Survey
		{
			get { return _survey; }
		}

		public void SetPendingCorrectOutcome(Response guessedAnswer)
		{
			_indPendingOutcome.OnSet();
			_pendingOutcome = new PendingCorrectOutcome(this, guessedAnswer);
		}

		public void SetPendingIncorrectOutcome()
		{
			_indPendingOutcome.OnSet();
			_pendingOutcome = new PendingIncorrectOutcome(this);
		}

		public void Abort()
		{
			if (_pendingOutcome != null)
			{
				_indPendingOutcome.OnSet();
				_pendingOutcome = null;
			}
		}

		public void Commit()
		{
			if (_pendingOutcome != null)
			{
				_pendingOutcome.Commit();
				_indPendingOutcome.OnSet();
				_pendingOutcome = null;
			}
		}

		public bool IsAnswerPending(Response answer)
		{
			_indPendingOutcome.OnGet();
			return _pendingOutcome != null && _pendingOutcome.IsAnswerPending(answer);
		}

		public bool IsIncorrectPending()
		{
			_indPendingOutcome.OnGet();
			return _pendingOutcome != null && _pendingOutcome.IsIncorrectPending();
		}

        public bool IsAnswerGuessed(Response answer)
		{
			_indGuessedAnswers.OnGet();
			return _guessedAnswers.Contains(answer);
		}

		public void GuessIncorrect()
		{
			_indIncorrectGuesses.OnSet();
			_incorrectGuesses++;
			if (_incorrectGuesses > 3)
				_incorrectGuesses = 1;
		}

		public int IncorrectGuesses
		{
			get { _indIncorrectGuesses.OnGet(); return _incorrectGuesses; }
		}

		public void AddGuessedAnswer(Response guessedAnswer)
		{
			_indGuessedAnswers.OnSet();
			_guessedAnswers.Add(guessedAnswer);
		}

		public override bool Equals(object obj)
		{
			if (obj == this)
				return true;
			RoundNavigation that = obj as RoundNavigation;
			if (that == null)
				return false;
			return object.Equals(this._survey, that._survey);
		}

		public override int GetHashCode()
		{
			return _survey.GetHashCode();
		}

		public void Dispose()
		{
		}
	}
}
